<template>
  <GoodsSkeleton v-if="loading"></GoodsSkeleton>
  <view v-else class="viewport">
    <!-- 商品主图 -->
    <view class="pics-con">
      <swiper class="swiper-picx" circular autoplay @change="onChange">
        <swiper-item class="swiper-item" v-for="(pic, index) in details?.mainPictures" :key="index">
          <image class="image" :src="pic" mode="aspectFill" @tap="onTapImage(pic)"></image>
        </swiper-item>
      </swiper>
      <view class="indicator">{{ current }}/{{ details?.mainPictures.length }}</view>
    </view>
    <!-- 商品简介 -->
    <view class="meta">
      <view class="price">
        <text class="symbol">￥</text>
        <text class="number">{{ details?.price }}</text>
      </view>
      <view class="title">{{ details?.name }}</view>
      <view class="desc">{{ details?.desc }}</view>
    </view>
    <!-- 操作面板 -->
    <view class="action-panel">
      <view class="item arrow">
        <text class="label">选择</text>
        <text class="text ellipsis" @tap="openSkuPopup(SkuMode.Both)">{{ selectArrText }}</text>
      </view>
      <view class="item arrow" @tap="openPopup('address')">
        <text class="label">送至</text>
        <text class="text ellipsis">{{ selectedAddress }}</text>
      </view>
      <view class="item arrow" @tap="openPopup('service')">
        <text class="label">服务</text>
        <text class="text ellipsis">无忧退 快速退款 免费包邮</text>
      </view>
    </view>
    <!-- uni-ui弹出层 -->
    <uni-popup ref="popup" type="bottom" background-color="#fff">
      <ServicePanel v-if="popupName === 'service'" @close="popup?.close()"></ServicePanel>
      <AddressPanel v-if="popupName === 'address'" @close="popup?.close()"></AddressPanel>
    </uni-popup>
    <!-- 商品详情 -->
    <view class="details-panel">
      <view class="title">详情</view>
      <view class="properties">
        <view class="item" v-for="(item, index) in details?.details.properties" :key="index">
          <text class="label">{{ item.name }}</text>
          <text class="value">{{ item.value }}</text>
        </view>
      </view>
      <!-- 图片详情 -->
      <view class="images">
        <image
          v-for="(img, index) in details?.details.pictures"
          :key="index"
          class="image"
          :src="img"
          mode="widthFix"
        ></image>
      </view>
    </view>
    <!-- 24h热销 -->
    <view class="hot-panel recommend-panel">
      <view class="green-title title">24h热销</view>
      <view class="container">
        <navigator
          class="prod"
          :url="`/pages/hot/hot?id=${hot.id}`"
          v-for="hot in details?.hotByDay"
          :key="hot.id"
        >
          <view class="recommend-card">
            <image class="image" :src="hot.picture" mode="aspectFill"></image>
            <view class="item-title"
              ><text class="text">{{ hot.name }} </text></view
            >
            <view class="price">
              <text class="symbol">￥</text>
              <text class="number">{{ hot.price }}</text>
            </view>
          </view>
        </navigator>
      </view>
    </view>
    <!-- 同类推荐 -->
    <view
      class="similar-panel recommend-panel"
      :style="{ paddingBottom: safeAreaInsets!.bottom + 60   + 'px' }"
    >
      <view class="green-title">同类推荐</view>
      <view class="container">
        <navigator
          class="prod"
          :url="`/pages/hot/hot?id=${sim.id}`"
          v-for="sim in details?.similarProducts"
          :key="sim.id"
        >
          <view class="recommend-card">
            <image class="image" :src="sim.picture" mode="aspectFill"></image>
            <view class="item-title"
              ><text class="text">{{ sim.name }} </text></view
            >
            <view class="price">
              <text class="symbol">￥</text>
              <text class="number">{{ sim.price }}</text>
            </view>
          </view>
        </navigator>
      </view>
    </view>
    <!-- 用户操作 -->
    <view class="toolbar" :style="{ paddingBottom: safeAreaInsets?.bottom + 'px' }">
      <view class="icons">
        <button class="icons-button">
          <text class="icon-heart"></text>
          收藏
        </button>
        <button class="icons-button" open-type="contact">
          <text class="icon-handset"></text>
          客服
        </button>
        <navigator url="/pages/cart/cart2" class="icons-button">
          <text class="icon-cart"></text>
          购物车
        </navigator>
      </view>
      <view class="buttons">
        <view class="add-cart" @tap="openSkuPopup(SkuMode.Cart)">加入购物车</view>
        <view class="payment" @tap="openSkuPopup(SkuMode.Buy)">立即购买</view>
      </view>
    </view>
    <!-- sku模块 -->
    <vk-data-goods-sku-popup
      ref="skuPopupRef"
      v-model="isShowSku"
      :localdata="localData"
      :mode="mode"
      add-cart-background-color="#FFA868"
      buy-now-background-color="#27BA9B"
      @add-cart="addCart"
      @buy-now="buyNow"
    ></vk-data-goods-sku-popup>
  </view>
</template>

<script lang="ts" setup>
import { onLoad } from '@dcloudio/uni-app'
import { computed, ref } from 'vue'
import Api from '@/services'
import type { IGoodsDetail } from '@/types/category'
import ServicePanel from './components/ServicePanel.vue'
import AddressPanel from './components/AddressPanel.vue'
import GoodsSkeleton from './components/GoodsSkeleton.vue'
import type {
  SkuPopupEvent,
  SkuPopupInstance,
  SkuPopupLocaldata,
} from '@/components/vk-data-goods-sku-popup/vk-data-goods-sku-popup'
import { useAddressStore } from '@/stores/modules/address'
enum SkuMode {
  Both = 1,
  Cart = 2,
  Buy = 3,
}

const details = ref<IGoodsDetail>()
const current = ref(1)
const loading = ref(true)
const popup = ref<{
  open: (type?: UniHelper.UniPopupType) => void
  close: () => void
}>()
const popupName = ref<'address' | 'service'>()
const isShowSku = ref(false)
const mode = ref<SkuMode>()
const localData = ref<SkuPopupLocaldata>()
const skuPopupRef = ref<SkuPopupInstance>()

// 获取屏幕边界到安全区域距离
const { safeAreaInsets } = uni.getSystemInfoSync()
const addressStore = useAddressStore()

const selectArrText = computed(() => {
  return skuPopupRef.value?.selectArr?.join(' ').trim() || '请选择商品规格'
})

const selectedAddress = computed(() => {
  const addressDetail = addressStore.selectedAddress
  if (addressDetail) {
    return `${addressDetail.fullLocation} ${addressDetail.address}`
  }
  return '请选择收获地址'
})

const getGoodsData = async (id: string) => {
  console.log('getGoods')
  const { result: data } = await Api.CategoryAPI.getGoodsDetail(id)
  details.value = data
  // 设置skuPopup
  localData.value = {
    _id: data.id,
    name: data.name,
    goods_thumb: data.mainPictures[0],
    spec_list: data.specs.map((i) => {
      return {
        name: i.name,
        list: i.values,
      }
    }),
    sku_list: data.skus.map((i) => {
      return {
        _id: i.id,
        goods_id: data.id,
        goods_name: data.name,
        image: i.picture!,
        price: Number(i.price) * 100,
        stock: i.inventory,
        sku_name_arr: i.specs.map((v) => v.valueName),
      }
    }),
  }
  console.log(localData, 'localData')
}

onLoad(async (options) => {
  loading.value = true
  const id = options?.id
  await getGoodsData(id!)
  loading.value = false
})

const onChange: UniHelper.SwiperOnChange = (event) => {
  current.value = event.detail.current + 1
}

const onTapImage = (url: string) => {
  // 大图预览
  uni.previewImage({
    current: url,
    urls: details.value!.mainPictures,
  })
}

const openPopup = (name: typeof popupName.value) => {
  console.log('触发')
  // 修改弹出层名称
  popupName.value = name
  // 打开弹出层
  popup.value?.open()
}

const openSkuPopup = (val: SkuMode) => {
  isShowSku.value = true
  mode.value = val
}

const addCart = async (ev: SkuPopupEvent) => {
  await Api.CartAPI.addCart({
    skuId: ev._id,
    count: ev.buy_num,
  })
  uni.showToast({
    title: '添加成功',
  })
  isShowSku.value = false
}

const buyNow = (ev: SkuPopupEvent) => {
  uni.navigateTo({ url: `/pagesOrder/orderPre/orderPre?skuId=${ev._id}&count=${ev.buy_num}` })
}
</script>

<style lang="scss" scoped>
@import './styles/goods.scss';
</style>
